import React, {useRef, useState, useEffect} from "react";
import {ScrollView, StyleSheet, Text, TouchableOpacity, View, Image, Share, Platform} from "react-native";
import {useCalculate} from "../../hooks/useCalculate";
import {showToast} from "../../utils/toast";
import {/*RFValue*/} from "react-native-responsive-fontsize";
import ViewShot from 'react-native-view-shot';
import RNFS from 'react-native-fs';
import RNShare from 'react-native-share';
import {ImageMap} from "../../constants/categories";
import {ArrowBackIcon, NativeBaseProvider} from "native-base";
import EmptyView from "../../components/EmptyView";
import * as S from "../Home/styles";
import SkeletonView from "../../components/Skeleton";
import {windowWidth} from "../../utils/config";
const shareIcon = require('../../assets/images/share.png')

const blueColor = 'rgba(48,118,217,1)';
const redColor = 'rgba(228,84,84,1)';

const OverView = (props) => {

    const [ calculatesOverview, setCalculateOverview ] = useState([]);
    const [ captureUrl, setCaptureUrl ] = useState('');
    const [loading, setLoading] = useState(true);
    const { loadCalculateOverview } = useCalculate();
    const viewRef = useRef();

    useEffect(() => {
        // props?.navigation.setOptions({
        //     headerTitle: props?.route?.params?.title,
        //     headerRight: renderHeaderRight,
        // });

        if (props?.route?.params?.dateTime?.length == 2) {
            loadCalculateOverview({
                startDate: props?.route?.params.dateTime[0],
                endDate: props?.route?.params.dateTime[1],
            }).then(function (response) {
                setLoading(false);
                if (response.code === 0) {
                    setCalculateOverview(response?.data?.events || []);
                } else {
                    showToast("error", "出错了", data?.msg || '请求失败');
                }
            });
        }

    }, []);

    const Title = ({navigation}:any)=>{
        return(
            <View style={styles.titleBox}>
                <TouchableOpacity
                    style={styles.backBtn}
                    onPress={() => {
                        navigation.goBack()
                    }}
                >
                    <ArrowBackIcon size="5" />
                </TouchableOpacity>
                <Text style={styles.titlText}>{props?.route?.params?.title}</Text>
                { loading ? null : renderHeaderRight()}
            </View>
        )
    }

    const renderHeaderRight = () => (
        <TouchableOpacity onPress={captureView} style={styles.headerRight}>
            <Image source={shareIcon} style={styles.shareIcon}/>
        </TouchableOpacity>
    );

    const captureView = () => {
        if (captureUrl) {
            shareImage(captureUrl);
        } else {
            viewRef?.current?.capture()
                .then((uri) => {
                    setCaptureUrl(uri);
                    shareImage(uri);
                })
                .catch((err) => {
                    showToast("error", "生成图片", '生成图片失败');
                });
        }
    };

    const shareImage = (imagePath) => {
        try {
            if (Platform.OS === 'ios') {
                Share.share({
                    // 对于网络图片，你需要先下载到本地，然后使用本地的URI
                    // 对于本地图片，直接使用本地的URI
                    url: imagePath,
                    // iOS上的标题
                    title: '图片分享',
                    // 可选的额外信息
                    message: '',
                }, {
                    // Android上的对话框标题
                    dialogTitle: '图片分享',
                    // 对于iOS的tintColor
                    tintColor: 'blue',
                    // Android上的可选配置
                    excludedActivityTypes: [
                        // 排除不想显示的分享选项
                    ],
                }).then((result)=>{
                    if (result.action === Share.sharedAction) {
                        if (result.activityType) {
                            // 分享成功，使用了特定的activityType
                        } else {
                            // 分享成功
                        }
                    } else if (result.action === Share.dismissedAction) {
                        // 分享被取消
                    }
                }).catch((err)=>{

                });

            } else {
                // 读取图片为base64格式
                RNFS.readFile(imagePath, 'base64').then((base64Image)=>{
                    const shareOptions = {
                        title: '图片分享',
                        message: '',
                        url: `data:image/png;base64,${base64Image}`, // 注意这里的MIME类型应该与你的图片类型相匹配
                        type: 'image/png',
                    };
                    RNShare.open(shareOptions).then((res)=>{
                    }).catch((error)=>{
                    });
                }).catch((err)=>{
                });
            }
        } catch (error) {
            console.error('Error sharing image: ', error);
        }
    };

    console.log('---overview--state-',calculatesOverview)


    const renderContent = () => {
        return(
            <View style={{backgroundColor: 'rgba(244, 244, 244, 1)',marginBottom: 40}}>
                <View style={{flexDirection: 'row',marginBottom: 10}}>
                    <Text style={styles.headerView}>一级</Text>
                    <Text style={styles.headerView}>二级</Text>
                    <Text style={styles.headerView}>三级</Text>
                    <Text style={styles.headerView}>计划h</Text>
                    <Text style={styles.headerView}>实际h</Text>
                    <Text style={styles.headerView}>差值</Text>
                </View>
                {calculatesOverview.map((item,index) => {
                    const url = ImageMap.find((image) => {
                        return image.name === item.icon;
                    })?.url;

                    let itemCount = 0;
                    let itemFixValue = ((item?.planTime || 0) - (item.usedTime || 0)).toFixed(1);
                    let itemFixColorStyle = [];
                    if (itemFixValue >= 0) {
                        itemFixColorStyle.push({color: blueColor})
                    } else {
                        itemFixColorStyle.push({color: redColor})
                    }

                    if (item?.children&&Array.isArray(item.children)) {
                        item.children.map((child,i)=>{
                            if (child?.children&&Array.isArray(child?.children)) {
                                itemCount += child?.children.length;
                            } else {
                                itemCount += 1;
                            }
                        })
                    } else {
                        itemCount += 1;
                    }

                    return (
                        <View key={'item_'+index} style={styles.contentItemView}>
                            <View style={[styles.contentItemTitle,{height: itemCount * 36 + (itemCount > 1 ? itemCount * 2 : 0)}]}>
                                {
                                    url ? <Image source={url} style={[styles.itemIcon,{marginBottom: itemCount > 1 ? 10 : 1}]}/>:null
                                }
                                <Text style={styles.contentItemName}>{item.name}</Text>
                            </View>
                            <View>
                                {
                                    item?.children&&Array.isArray(item.children) ? item.children.map((child,i)=>{
                                            let childFixValue = ((child?.planTime || 0) - (child.usedTime || 0)).toFixed(1);
                                            let childFixColorStyle = [];
                                            if (childFixValue >= 0) {
                                                childFixColorStyle.push({color: blueColor})
                                            } else {
                                                childFixColorStyle.push({color: redColor})
                                            }
                                            return (
                                                <View key={'children_'+i}>
                                                    <View style={{flexDirection: 'row'}}>
                                                        <View style={[styles.contentItemSubTitle,{borderBottomWidth: i == item.children.length-1 ? 0 : 1}]}>
                                                            <Text style={styles.contentItem}>{child.name}</Text>
                                                        </View>
                                                        <View>
                                                            {
                                                                child?.children&&Array.isArray(child?.children)? child.children.map((seg,j)=>{
                                                                        let fiValue = ((seg?.planTime || 0) - (seg.usedTime || 0)).toFixed(1);
                                                                        let colorStyle = [];
                                                                        if (fiValue >= 0) {
                                                                            colorStyle.push({color: blueColor})
                                                                        } else {
                                                                            colorStyle.push({color: redColor})
                                                                        }
                                                                        return (
                                                                            <View style={{flexDirection: 'row'}} key={index+'childSeg_'+i+'sub_'+j}>
                                                                                <Text style={[styles.contentItem]}>{seg.name}</Text>
                                                                                <Text style={[styles.contentItem]}>{seg.planTime}</Text>
                                                                                <Text style={[styles.contentItem]}>{seg.usedTime}</Text>
                                                                                <Text style={[styles.contentItem,colorStyle]}>{fiValue}</Text>
                                                                            </View>
                                                                        )
                                                                    }):
                                                                    <View style={{flexDirection: 'row'}}>
                                                                        <Text style={[styles.contentItem]}></Text>
                                                                        <Text style={[styles.contentItem]}>{child.planTime}</Text>
                                                                        <Text style={[styles.contentItem]}>{child.usedTime}</Text>
                                                                        <Text style={[styles.contentItem,childFixValue]}>{childFixValue}</Text>
                                                                    </View>
                                                            }
                                                        </View>
                                                    </View>

                                                </View>
                                            )
                                        }):
                                        <View style={{flexDirection: 'row'}}>
                                            <Text style={[styles.contentItem]}></Text>
                                            <Text style={[styles.contentItem]}></Text>
                                            <Text style={[styles.contentItem]}>{item.planTime}</Text>
                                            <Text style={[styles.contentItem]}>{item.usedTime}</Text>
                                            <Text style={[styles.contentItem,itemFixColorStyle]}>{itemFixValue}</Text>
                                        </View>
                                }
                            </View>

                        </View>
                    );
                })}
            </View>
        )
    }

    return (
        <S.GrayContainer>
            <NativeBaseProvider >
                <View style={{ flex: 1,backgroundColor: 'rgba(244, 244, 244, 1)'}}>
                    <Title navigation={props?.navigation}/>
                    {/*{*/}
                    {/*    captureUrl?<Image source={{uri: captureUrl}} resizeMode={'contain'} style={{width: '100%',height: 675}}/>:null*/}
                    {/*}*/}
                    {
                        loading ? <SkeletonView/> :
                        calculatesOverview.length === 0 ? <EmptyView/> :
                            <View>
                                <View>
                                    <ScrollView showsHorizontalScrollIndicator={false} horizontal>
                                        <ScrollView showsVerticalScrollIndicator={false}>
                                            {renderContent()}
                                        </ScrollView>
                                    </ScrollView>
                                </View>

                                <View style={{position: 'absolute',left: windowWidth*2}}>
                                    <ViewShot ref={viewRef}>
                                        <View>
                                            {renderContent()}
                                        </View>
                                    </ViewShot>
                                </View>

                            </View>
                    }
                </View>
            </NativeBaseProvider>
        </S.GrayContainer>
    );
};

export default OverView;

const styles = StyleSheet.create({
    levelOne: {
        marginHorizontal: 18,
    },
    headerView: {
        width: 72,
        height: 36,
        backgroundColor: 'rgba(232,232,232,1)',
        margin: 1,
        textAlign: 'center',
        paddingTop: 10,
        fontSize: 12,
        color: 'rgba(72, 72, 74, 1)',
        fontWeight: 'bold'
    },
    contentItemView: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    itemIcon: {
        width: 20,
        height: 20,
    },
    contentItemTitle: {
        width: 72,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        borderRightWidth: 1,
        borderRightColor: 'rgba(232,232,232,1)',
    },
    contentItemName: {
        width: 72,
        backgroundColor: '#fff',
        margin: 1,
        textAlign: 'center',
        fontSize: 12,
        color: 'rgba(44, 44, 46, 1)'
    },
    contentItemSubTitle: {
        width: 72,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomColor: 'rgba(232,232,232,1)'
    },
    contentItem: {
        width: 72,
        height: 36,
        backgroundColor: '#fff',
        margin: 1,
        textAlign: 'center',
        paddingTop: 10,
        fontSize: 12,
        color: 'rgba(44, 44, 46, 1)'
    },
    titleBox:{
        width:'100%',
        position:'relative',
        alignItems:'center',
        height:40,
        justifyContent:"center",
        marginBottom:16,
        paddingHorizontal: 16,
    },
    backBtn:{
        position:'absolute',
        left:16,
        backgroundColor:'#fff',
        width:40,
        height:40,
        display:'flex',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:100,

        shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
        shadowOffset: { width: 0, height: 2 }, // 阴影偏移
        shadowOpacity: 1, // 阴影不透明度
        shadowRadius: 8, // 阴影半径
        elevation: 3, // 阴影深度
    },
    headerRight: {
        position:'absolute',
        right:16,
        backgroundColor:'#fff',
        width:40,
        height:40,
        display:'flex',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:100,
    },
    titlText:{
        fontSize:16,
        fontWeight:'600',
        color:'#000000'
    },
    shareIcon: {
        width: 24,
        height: 24,
    },
});